
<template>
  <!-- 营销项目案例管理-优秀案例评选 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="conditionFilter"
      :list="topFilterInit"
      :cols="3"
      labelWidth="120"
      @filterChange="changeHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
      columnsRef="projectOperating_case_allInquire_index_01"
    >
      <template slot="controls">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="requestExportData"
        >下载</el-button>
      </template>
    </FilterTable>

    <!-- 经销商弹窗 -->
    <BaseDialog
      title="经销商查询"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealerMadal
        selectType="multiple"
        v-model="initDealerData"
        ref="dealerDialog"
        @close="closeDealer"
      />
    </BaseDialog>

    <!--明细弹窗-->
    <Drawer
      :visible.sync="visibleDrawerEdit"
      :title="dialogTitleAdd"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <infoEdit-modal :type="handleTypeAdd" :rowEditData="formEditData" @close="closeHandler" />
    </Drawer>
  </div>
</template>

<script>
import { exportExcelFile } from '@/utils/index';
// import dealerMadal from '../departmentReport/dealerMadal';
import dealerMadal from '@/pages/cms-common/dealerdata';
import infoEditModal from './infoEdit';
import { dictionary } from '@/utils/dictMixin';
import { getRegion } from '@/api/cms-common/dealerdata/index';
import { formatdateByDay, parseTime } from '@/utils/index';
import { getOutStandingList, selectListByBill, selectALListByBill, getOutCaseExcelList } from '@/api/cms-api/projectOperating/case/oemCollect/index';
export default {
  mixins: [dictionary],
  components: {
    dealerMadal,
    infoEditModal
  },
  //初始化数据  全局变量
  data() {
    return {
      topFilterInit: this.topFilterInitFun(),
      visibleDealer: false,
      columns: this.creatHeader(),
      isSelectColumn: false,
      fetchApi: getOutStandingList, //ipa 接口
      fetchParams: {
        caseStatus: 25351003
      }, //参数
      visibleDrawerEdit: false,
      exportLoading: false,
      initDealerData: {}, //经销商弹窗参数,
      dataSource: [], //返回经销商数组
      dialogTitleAdd: '',
      handleTypeAdd: '',
      formEditData: {},
      month: '', //当前月份第一天
      monthLast: '' //当前月份最后一天
    };
  },
  //方法、事件
  methods: {
    //导出
    async requestExportData() {
      let r = await this.$refs.conditionFilter.GET_FORM_DATA();
      let p = null;
      if (r != null && r.length > 1) {
        p = r[1];
      }
      this.exportLoading = true;
      p = Object.assign({}, { caseStatus: 25351003 }, p);
      let time = p.projectExecuteStartDate;
      //修改时间后
      // if ((formatdateByDay(time[0]) == formatdateByDay(this.month) && formatdateByDay(time[1]) == formatdateByDay(this.monthLast)) || time.length == 0) {
      //   p = Object.assign({}, { timestart: formatdateByDay(this.month) }, p);
      //   p = Object.assign({}, { timeend: formatdateByDay(this.monthLast) }, p);
      // } else {
      p = Object.assign({}, { timestart: time[0] }, p);
      p = Object.assign({}, { timeend: time[1] }, p);
      // }
      this.exportLoading = true;
      // this.$refs.conditionFilter.SUBMIT_FORM();
      getOutCaseExcelList(p).then(res => {
        exportExcelFile(res.data, '全国优秀案例查询');
        this.exportLoading = false;
      });
    },
    //搜索回调
    changeHandle(data) {
      let time = data.projectExecuteStartDate;
      // if ((formatdateByDay(time[0]) == formatdateByDay(this.month) && formatdateByDay(time[1]) == formatdateByDay(this.monthLast)) || time.length == 0) {
      //   data = Object.assign({}, { timestart: formatdateByDay(this.month) }, data);
      //   data = Object.assign({}, { timeend: formatdateByDay(this.monthLast) }, data);
      // } else {
      data = Object.assign({}, { timestart: time[0] }, data);
      data = Object.assign({}, { timeend: time[1] }, data);
      // }
      data = Object.assign({}, { caseStatus: 25351003 }, data);
      data = Object.assign({}, { dealerCode: this.dealerCode }, data);
      this.dealerCode = '';
      this.fetchParams = Object.assign({}, data);
    },
    closeHandler(val, type) {
      this.visibleDrawerEdit = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    //明细
    async drawerHandle(row, type) {
      this.formEditData = row;
      this.dialogTitleAdd = `全国优秀案例明细`;
      //征集附件
      let res = {};
      let fileParams = { caseLevyId: this.formEditData.caseLevyId, billType: 25681001 };
      res = await selectListByBill(fileParams);
      if (res.data.length > 0) {
        let caseUrlList = [];
        for (let j = 0; j < res.data.length; j++) {
          let o1 = { name: res.data[j].fileName };
          let o2 = { url: res.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList.push(a);
        }
        this.formEditData = Object.assign({}, { collectFile: caseUrlList }, this.formEditData);
      }
      //项目附件
      let res1 = {};
      let fileParams1 = { caseId: this.formEditData.caseId, billType: 25681002 };
      res1 = await selectALListByBill(fileParams1);
      if (res1.data.length > 0) {
        let caseUrlList1 = [];
        for (let j = 0; j < res1.data.length; j++) {
          let o1 = { name: res1.data[j].fileName };
          let o2 = { url: res1.data[j].fileId };
          let a = Object.assign(o1, o2);
          caseUrlList1.push(a);
        }
        this.formEditData = Object.assign({}, { projectFile: caseUrlList1 }, this.formEditData);
      }
      this.visibleDrawerEdit = true;
    },
    //打开经销商弹窗
    openDialog() {
      this.initDealerData = {
        excludeBigCustomer: false, //是否查询大客户经销商，如果查询 true，不查询 false
        id: 1001
      };
      this.visibleDealer = true;
    },
    //经销商窗口关闭，返回数据
    closeDealer(data) {
      if (data.data && data.data.length > 0) {
        //清空数据内容
        this.dealerCode = '';
        this.dealerName = '';
        //循环返回数据
        data.data.forEach(x => {
          //插入经销商id
          // this.dealerList.push(x.dealerId);
          //使用逗号分隔拼接经销商ID
          if (this.dealerCode == '') {
            this.dealerCode = x.dealerCode;
          } else {
            this.dealerCode += ',' + x.dealerCode;
          }

          // this.dealerList.push(x.dealerId);
          //使用逗号分隔拼接经销商名称
          if (this.dealerName == '') {
            this.dealerName = x.dealerName;
          } else {
            this.dealerName += ',' + x.dealerName;
          }
        });
        this.topFilterInit[6].initialValue = this.dealerName;
      }
      this.visibleDealer = data.visible; //关闭弹窗
    },
    //获取事业部下拉列表数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.topFilterInit[7].itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'INPUT', label: '优秀案例编号', fieldName: 'caseCode', initialValue: '' },
        { type: 'INPUT', label: '项目编号', fieldName: 'planCode', initialValue: '' },
        { type: 'INPUT', label: '项目名称', fieldName: 'projectName', initialValue: '' },
        { type: 'INPUT', label: '优秀案例征集编号', fieldName: 'caseLevyCode', initialValue: '' },
        { type: 'INPUT', label: '优秀案例征集名称', fieldName: 'caseLevyName', initialValue: '' },
        {
          type: 'RANGE_DATE',
          label: '项目开始时间',
          fieldName: 'projectExecuteStartDate',
          initialValue: []
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openDialog()}></el-button>;
          }
        },
        { type: 'SELECT', label: '事业部', fieldName: 'businessId', placeholder: '请选择', initialValue: '', itemList: [] }
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row, 'show')}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        // {
        //   title: '评选状态',
        //   dataIndex: 'caseStatus',
        //   sorter: true,
        //   hidden: true,
        //   filterItems: this.createDictList('2535'),
        //   render: props => {
        //     //编码转汉字
        //     return <span>{this.createDictText(props.row.caseStatus, '2535')}</span>;
        //   }
        // },
        // {
        //   title: '事业部',
        //   dataIndex: 'businessId',
        //   sorter: true,
        //   hidden: true
        // },
        {
          title: '事业部',
          dataIndex: 'orgName',
          sorter: true
        },
        {
          title: '经销商编号',
          dataIndex: 'ownerCode',
          sorter: true
        },
        {
          title: '经销商简称',
          dataIndex: 'dealerShortname',
          sorter: true
        },
        {
          title: '经销商全称',
          dataIndex: 'dealerName',
          sorter: true
        },
        {
          title: '优秀案例编号',
          dataIndex: 'caseCode',
          sorter: true
        },
        {
          title: '案例征集编号',
          dataIndex: 'caseLevyCode',
          sorter: true
        },
        { title: '案例征集名称', dataIndex: 'caseLevyName', sorter: true },
        { title: '项目编号', dataIndex: 'planCode', sorter: true },
        { title: '项目名称', dataIndex: 'projectName', sorter: true },
        {
          title: '征集开始时间',
          dataIndex: 'levyStartDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.levyStartDate)} </span>;
          }
        },
        {
          title: '征集结束时间',
          dataIndex: 'levyEndDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.levyEndDate)} </span>;
          }
        },
        {
          title: '项目开始时间',
          dataIndex: 'projectExecuteStartDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.projectExecuteStartDate)} </span>;
          }
        },
        {
          title: '项目结束时间',
          dataIndex: 'projectExecuteEndDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.projectExecuteEndDate)} </span>;
          }
        }
        // {
        //   title: '提交时间',
        //   dataIndex: 'reportDate',
        //   sorter: true,
        //   hidden: true,
        //   render: props => {
        //     return <span>{this.formatDates(props.row.reportDate)} </span>;
        //   }
        // },
        // { title: '评选建议', dataIndex: 'selectionSuggest', sorter: true, hidden: true }
      ];
    },
    formatDates: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + '-' + month + '-' + day;
    },
    getMonthNow() {
      // let now = new Date();
      // let month = now.getMonth(); //获取当前月份
      // let year = now.getFullYear();
      // let nextMonthFirstDay = new Date(year, month + 1, 1).getTime(); //获取下个月第一天
      // let oneDay = 1000 * 24 * 60 * 60;
      // let monthLast = new Date(nextMonthFirstDay - oneDay); //计算当前月最后一天
      // this.month = parseTime(new Date(year, month, 1), '{y}-{m}-{d} {h}:{i}:{s}');
      // this.monthLast = parseTime(monthLast, '{y}-{m}-{d} {h}:{i}:{s}');
      // this.topFilterInit[5].initialValue = [this.month, this.monthLast];
      // this.fetchParams = Object.assign({}, this.fetchParams, { timestart: this.month, timeend: this.monthLast });
      let nDay = new Date(); //当日
      let m3Day = new Date(); //当前前三月日期
      m3Day.setMonth(m3Day.getMonth() - 3);
      //初始化分配时间
      //初始化分配时间
      let _3monthDate = parseTime(m3Day, '{y}-{m}-{d} {h}:{i}:{s}');
      let currentDate = parseTime(nDay, '{y}-{m}-{d} {h}:{i}:{s}');
      this.topFilterInit[5].initialValue = [_3monthDate, currentDate];
      this.fetchParams = Object.assign({}, this.fetchParams, { timestart: _3monthDate, timeend: currentDate });
    }
  },
  created() {
    //获取事业部下拉列表
    this.getDeptData();
    //默认取当前月份
    this.getMonthNow();
  }
};
</script>

<style scoped>
</style>
